package com.mySampleApplication.server.database;

import com.mySampleApplication.client.User;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * Created by Navuhodonosor on 12/14/2014.
 */
public class UserDaoImpl implements UserDao {

    @PersistenceContext
    private EntityManager entityManager;


    @Override
    public void add(User user) {
        entityManager.persist(user);
    }

    @Override
    public void update(User user) {
        entityManager.merge(user);
    }

    @Override
    public void delete(User user) {
        entityManager.remove(entityManager.getReference(User.class,user.getId()));
    }

    @Override
    public List<User> getUsers(String search) {
        if (null == search || search.trim().isEmpty()){
            return entityManager.createQuery("select u from User u").getResultList();
        }
        return entityManager.createQuery("select u from User u where u.name like :search").setParameter("search",search.trim()+ "%").getResultList();
    }
}
